<template>
    <lay-layout :class="[collapseState ? 'collapse' : '']">
      <!-- header 系统切换栏 -->
      <lay-header class="layui-header">
        <lay-menu class="layui-layout-left">
          <lay-menu-item>
            <img src="/ico/logo_hs_s.png">
          </lay-menu-item>
          <lay-menu-item>
            <template #title>
              <span style="font-size: 25px;font-weight: bolder;color: #dee7f8;margin-top: 30px">数风测试平台</span>
            </template>
          </lay-menu-item>
          <lay-menu-item @click="refresh">
            <lay-icon type="layui-icon-refresh-one"></lay-icon>
          </lay-menu-item>
          <lay-menu-item
              @click="setSystem('FirstPage')"
              :class="system === 'FirstPage' ? 'click-sub-system' : 'no-click-sub-system'"
          >
            <template #title>
              <span><lay-icon type="layui-icon-app"></lay-icon>首页</span>
            </template>
          </lay-menu-item>
          <lay-menu-item
              @click="setSystem('dataMock')"
              v-if="appStore.mock_data"
              :class="system === 'dataMock' ? 'click-sub-system' : 'no-click-sub-system'"
          >
            <template #title>
              <span><lay-icon type="layui-icon-app"></lay-icon>数据模拟工具</span>
            </template>
          </lay-menu-item>
          <lay-menu-item
              @click="setSystem('marketMock')"
              v-if="appStore.mock_market"
              :class="system === 'marketMock' ? 'click-sub-system' : 'no-click-sub-system'"
          >
            <template #title>
              <span><lay-icon type="layui-icon-app"></lay-icon>交易所模拟</span>
            </template>
          </lay-menu-item>
          <lay-menu-item
              @click="setSystem('excelCase')"
              v-if="appStore.excel_case"
              :class="system === 'excelCase' ? 'click-sub-system' : 'no-click-sub-system'"
          >
            <template #title>
              <span><lay-icon type="layui-icon-app"></lay-icon>测试服务</span>
            </template>
          </lay-menu-item>
          <lay-menu-item
              @click="setSystem('dataGenerator')"
              v-if="appStore.data_generator"
              :class="system === 'dataGenerator' ? 'click-sub-system' : 'no-click-sub-system'"
          >
            <template #title>
              <span><lay-icon type="layui-icon-app"></lay-icon>数据仿真</span>
            </template>
          </lay-menu-item>

        </lay-menu>
        <lay-menu class="layui-layout-right">
            <lay-menu-item>
              <lay-dropdown :trigger="['hover','click']" updateAtScroll>
                <lay-button size="sm" style="width: 120px" radius>
                  <template #default><h3>{{productName}}</h3></template>
                </lay-button>
                <template #content>
                    <lay-dropdown-menu>
                      <lay-dropdown-menu-item v-for="item in user.product.list" @click="changProduct(item)">{{item.name}}</lay-dropdown-menu-item>
                    </lay-dropdown-menu>
                </template>
              </lay-dropdown>
            </lay-menu-item>
            <lay-dropdown>
              <lay-menu-item>
                <lay-icon type="layui-icon-notice"></lay-icon>
              </lay-menu-item>
              <template #content>
                <lay-dropdown-menu>
                  <lay-dropdown-menu-item>版本信息：{{version.id}}</lay-dropdown-menu-item>
                  <lay-dropdown-menu-item>版本时间：{{version.date}}</lay-dropdown-menu-item>
                </lay-dropdown-menu>
              </template>
            </lay-dropdown>
            <lay-dropdown>
              <lay-menu-item>
                <lay-icon type="layui-icon-username"></lay-icon>
              </lay-menu-item>
              <template #content>
                <lay-dropdown-menu>
                  <lay-dropdown-menu-item @click="viewUserInfo">用户信息</lay-dropdown-menu-item>
                  <lay-dropdown-menu-item @click="modifyPwd">更新密码</lay-dropdown-menu-item>
                  <lay-dropdown-menu-item @click="logout_btn">注销登录</lay-dropdown-menu-item>
                  <lay-dropdown-menu-item @click="clearLocalStorage">清理缓存</lay-dropdown-menu-item>
                </lay-dropdown-menu>
              </template>
            </lay-dropdown>
            <lay-dropdown>
              <lay-menu-item>
                <lay-icon type="layui-icon-service" @click="visible2 = !visible2"></lay-icon>
              </lay-menu-item>
            </lay-dropdown>
            <div style="position: relative; display: inline-block">
              <lay-menu-item @click="changeVisible">
                <lay-icon type="layui-icon-more-vertical"></lay-icon>
              </lay-menu-item>
            </div>
          </lay-menu>
      </lay-header>
      <lay-layout>
        <!-- side -->
        <lay-side :width="sideWidth" style="height: 100%" v-if="viewFlag">
          <lay-scroll style="height: calc(100% - 62px)">
            <global-menu :collapse="collapseState" :system="system" v-if="system === 'dataMock'"></global-menu>
            <global-menu :collapse="collapseState" :system="system" v-if="system === 'marketMock'"></global-menu>
            <global-menu :collapse="collapseState" :system="system" v-if="system === 'excelCase'"></global-menu>
          </lay-scroll>
          <div style="background: #ffffff;height: 62px">
            <lay-affix :target="target" :offset="0" position="bottom" v-if="target">
              <lay-button type="normal"  @click="collapse"><lay-icon
                v-if="collapseState"
                type="layui-icon-spread-left"
              ></lay-icon>
              <lay-icon v-else type="layui-icon-shrink-right"></lay-icon>
              </lay-button>
            </lay-affix>
          </div>
        </lay-side>
        <lay-body>
          <global-tab :style="{display: viewFlag ? 'block': 'none'}"></global-tab>
          <global-content></global-content>
        </lay-body>
      </lay-layout>
    </lay-layout>
    <global-setup v-model="visible"></global-setup>
    <RobotMan v-model="visible2"></RobotMan>
</template>

<script lang="ts">
import DarkIcon from "../components/DarkIcon.vue"
import LightIcon from "../components/LightIcon.vue"
import GlobalSetup from "./Global/GlobalSetup.vue";
import GlobalContent from "./Global/GlobalContent.vue";
import GlobalTab from "./Global/GlobalTab.vue";
import GlobalMenu from "./Global/GlobalMenu.vue";
import userInfos from "../components/System/userInfos.vue";
import robotMan from "../components/System/robotMan.vue";
import modifyPassWord from "../components/System/modifyPwd.vue";
import TestCaseLink from "../views/ThirdPartTools/TestCase/TestCaseLink.vue";
import UploadExcel from "../views/ThirdPartTools/FastApi/UploadExcel.vue";

export default {
  components: {
    GlobalSetup,
    GlobalContent,
    GlobalTab,
    GlobalMenu,
    DarkIcon,
    LightIcon,
    userInfos,
    modifyPassWord,
    robotMan,
    TestCaseLink,
    UploadExcel
  }
};
</script>

<script lang="ts" setup>
import {useRouter} from "vue-router";
import {useAppStore} from "../store/app";
import {userStore} from "../store/user";
import {h, onMounted, reactive, nextTick, ref} from "vue";
import {layer} from "@layui/layui-vue";
import {getProducts, logout, updateUser, viewUser} from "../api/module/user";
import userInfos from "../components/System/userInfos.vue";
import {notify} from "../untils/tip";
import DataGenerator from "../views/Generator/index.vue";
import AiDeepseek from "../views/EasyManager/index.vue";
import EasyManager from "../views/EasyManager/index.vue";
import EasyManagerTool from "../views/EasyManager/index.vue";

const childFlag = ref(false)
const router = useRouter();
const appStore = useAppStore();
const user = userStore();
const collapseState = ref(false);
const system = ref('dataMock');
const visible = ref(false);
const sideWidth = ref("230px");
const version = reactive({id: 'V2.0.0', date: '2025-01-02'})
const visible2 = ref(false);
const productName = ref('');
const viewFlag = ref(false)

const target=ref()
nextTick(()=>{
  target.value=document.querySelector(".layui-body");
})

const changeVisible = function () {
  visible.value = !visible.value;
};

// 侧边状态
const collapse = function () {
  collapseState.value = !collapseState.value;
  sideWidth.value = collapseState.value ? "60px": "230px";
};

const setSystem = (val: string) => {
  system.value = val;
  if(val === 'dataGenerator'){
    viewFlag.value = false;
    router.push('/generator');
  }else if(val === 'excelCase'){
    viewFlag.value = true;
    router.push('/aml/change');
    queryUserDetail();
  }else if(val === 'dataMock'){
    viewFlag.value = true;
    router.push('/scene/create');
  }else if(val === 'marketMock'){
    viewFlag.value = true;
    router.push('/record/encode');
  }else if(val === 'managerTool'){
    viewFlag.value = false;
    router.push('/manager/tool');
    console.log('跳转过去！')
  }else{
    viewFlag.value = false;
    router.push('/home');
  }
};


// 路由刷新
const refresh = function () {
  appStore.routerAlive = false;
  setTimeout(function () {
    appStore.routerAlive = true;
  }, 500);
};

const logout_btn = async () => {
    const user_detail: any = localStorage.getItem('user_detail');
    const user_info_cur = JSON.parse(user_detail);
    const params = reactive({user_no: user_info_cur.user_no});
    console.log(params)
    let {result, status, message} = await logout(params);
    if(status === 'success'){
        localStorage.removeItem('token')
        localStorage.removeItem('userInfo')
        user.userInfo = {};
        user.token = "";
        localStorage.removeItem('user_detail')
        localStorage.removeItem('robotMessage')
        clearLocalStorage();
    }else {
      notify(status, message);
    }
    router.push('/user/login')
};

const queryUserDetail = async () => {
    const user_detail = localStorage.getItem('user_detail');
    if(user_detail){
        const user_info_cur = JSON.parse(user_detail);
        let {result, status, message} = await viewUser({user_no: user_info_cur.user_no});
        if (status === 'success') {
            productName.value = result.tenant.name;
            user.product.tenant = result.tenant.id;
            user.userInfo = result;
            localStorage.setItem('user_detail', JSON.stringify(result))
        }else {
            layer.msg(message);
        }
    }else {
        await router.push('/user/login')
    }
}

const getCurUserInfo = async () => {
    const user_detail = localStorage.getItem('user_detail');
    console.log('user_detail:', user_detail)
    if(user_detail) {
      const user_info_cur = JSON.parse(user_detail);
      console.log(user_info_cur)
      let {result, status, message} = await getProducts({user_no: user_info_cur.user_no});
      if (status === 'success') {
        user.product.list = result;
      } else {
        layer.msg(message);
      }
      await queryUserDetail();
    }else{
      await router.push('/user/login')
    }
}

onMounted(() => {
    getCurUserInfo();
})


const changProduct = async (node: any) => {
  productName.value = node.name;
  const user_detail: any = localStorage.getItem('user_detail');
  const user_info_cur = JSON.parse(user_detail);
  const userParams = reactive({
    user_no: user_info_cur.user_no,
    username: user_info_cur.username,
    tenant: node.id});
  let {result, status, message} = await updateUser(userParams);
  if(status == 'success'){
      await router.push('/user/login')
      clearLocalStorage();
      await queryUserDetail();
      refresh();
      location.reload();
      window.location.reload();
  }else {
      layer.msg(message);
  }
};

// 清理缓存
const clearLocalStorage = () => {
  localStorage.removeItem('links');
  localStorage.removeItem('linksExpend');
  localStorage.removeItem('sceneTree');
  localStorage.removeItem('sceneTreeExpend');
  localStorage.removeItem('robotMessage');
  localStorage.removeItem('user_detail');
  localStorage.removeItem('token');
  localStorage.removeItem('userInfo');
};

const viewUserInfo = async () => {
    const user_detail: any = localStorage.getItem('user_detail');
    const user_info_cur = JSON.parse(user_detail);
    let {result, status, message} = await viewUser({user_no: user_info_cur.user_no});
    if (status === 'success') {
        const user_info = result;
        layer.open({
            type: "page",
            area: ['370px','400px'],
            title: '用户信息',
            content: h(userInfos, { user_info }),
        })
    }else {
        layer.msg(message);
    }
};

const modifyPwd = async () => {
    const user_detail: any = localStorage.getItem('user_detail');
    const user_info_cur = JSON.parse(user_detail);
    const user_no = user_info_cur.user_no;
    layer.open({
        area: ['400px','400px'],
        title: '更新用户密码',
        content: h(modifyPassWord, { user_no }),
    })
}

</script>

<style>
.layui-header {
    background-color: #1E9FFF !important;
    margin-top: -8px;
}
.layui-layout .layui-form-switch {
  /*border: 1px solid rgba(60, 60, 60, 0.29);*/
  background-color: #f1f1f1 !important;
  margin-top: -8px;
}
.layui-layout .layui-header .layui-form-switch svg {
  position: absolute;
  width: 12px;
  height: 12px;
  top: 3px;
  left: 3px;
}

.click-sub-system {
  font-size: medium;
  font-weight: bold;
  background-color: #5179f8;
}
.no-click-sub-system {
  font-size: small;
}
</style>